package evs.location;

import java.io.Serializable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class DeleteRequestHandler extends AbstractRequestHandler
{

    public DeleteRequestHandler( HttpServletRequest request, SessionFactory sessionFactory,
                    List<Class<?>> interceptorClasses, EntityMap entityMap ) throws EvsException
    {
        super( request, sessionFactory, interceptorClasses, entityMap );
    }

    @Override
    protected void _execute( HttpServletResponse response ) throws EvsException
    {
        if ( _entityId == null )
            throw new EvsException( HttpServletResponse.SC_BAD_REQUEST, "Entity ID missing." );
        
        Session session = null;
        Transaction tx = null;
        
        try
        {
            Class<?> expectedEntityClass = _getExpectedEntityClass();
            
            session = _sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Serializable id = _entityMap.convertId( expectedEntityClass, _entityId );
            
            Object entity = session.get( expectedEntityClass, id );
            session.delete( entity );
            
            tx.commit();
            tx = null;
            
            response.setStatus( HttpServletResponse.SC_OK );
        }
        catch ( HibernateException e )
        {
            e.printStackTrace();
            throw new EvsException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Hibernate error: " + e.getMessage() );
        }
        finally
        {
            if ( tx!= null )
            {
                tx.rollback();
                tx = null;
            }
            
            if ( session != null )
            {
                session.close();
            }
        }
    }

    @Override protected boolean allowUnknownMediaType() { return true; }   
}
